<template>
  <div class="user-comments">
    <h2 class="section-title">我的评论</h2>

    <!-- 评论列表 -->
    <div v-loading="loading">
      <div v-if="comments.length === 0" class="empty-state">
        <el-empty description="暂无评论记录" />
      </div>
      <div v-else>
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-product">
            <el-image 
              :src="comment.productImage || 'https://via.placeholder.com/80'" 
              class="product-image" 
              fit="cover"
              @click="goToProduct(comment.productId)"
            />
            <div class="product-info">
              <h3 class="product-name" @click="goToProduct(comment.productId)">{{ comment.productName || '商品名称' }}</h3>
              <div class="product-description" v-if="comment.description">{{ comment.description }}</div>
              <div class="product-price" v-if="comment.price">¥{{ comment.price.toFixed(2) }}</div>
              <div class="comment-date">评论时间：{{ formatDate(comment.createdAt) }}</div>
            </div>
          </div>
          
          <div class="comment-content">
            <div class="rating-row">
              <el-rate 
                v-model="comment.rating" 
                disabled 
                show-score 
                text-color="#ff4d4f"
                score-template="{value} 分"
              />
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            
            <!-- 评论图片 -->
            <div v-if="comment.imageUrls && comment.imageUrls.length > 0" class="comment-images">
              <el-image 
                v-for="(img, index) in comment.imageUrls" 
                :key="index" 
                :src="img" 
                fit="cover"
                :preview-src-list="comment.imageUrls"
                class="comment-image"
              />
            </div>
          </div>
          
          <div class="comment-actions">
            <el-button 
              type="danger" 
              plain 
              size="small" 
              @click="deleteComment(comment.id)"
              :loading="deleteLoading === comment.id"
            >
              删除评论
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
      
      <!-- 加载更多按钮 -->
      <div class="load-more-container" v-if="total > comments.length && currentPage < Math.ceil(total / pageSize)">
        <el-button 
          type="primary" 
          plain 
          @click="loadMore" 
          :loading="loadMoreLoading"
        >
          加载更多评论
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCommentsByUserId, deleteComment as deleteCommentApi } from '@/api/comments'

const router = useRouter()
const comments = ref([])
const loading = ref(false)
const deleteLoading = ref(null)
const loadMoreLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载用户评论
const loadComments = async () => {
  try {
    loading.value = true
    
    // 调用获取用户评论列表API
    // 根据接口文档: /comments/user, method: get, params: page, pageSize
    const data = await getCommentsByUserId(currentPage.value, pageSize.value)
    
    // 处理分页信息
    total.value = data?.total || 0
    
    // 处理评论数据
    if (data?.records && Array.isArray(data.records)) {
      comments.value = data.records.map(comment => {
        // 从spuVO中获取商品信息
        const spu = comment.spuVO || {}
        
        return {
          id: comment.id,
          productId: comment.spuId, // 使用spuId作为商品ID
          productName: spu.title || '未知商品',
          productImage: spu.mainImage || 'https://via.placeholder.com/80',
          content: comment.content || '',
          rating: comment.rating || 5,
          createdAt: comment.createdAt || new Date().toISOString(),
          imageUrls: Array.isArray(comment.imageUrls) ? comment.imageUrls : [],
          price: spu.price, // 添加商品价格
          description: spu.description // 添加商品描述
        }
      })
    } else {
      comments.value = []
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    ElMessage.error('加载评论失败，请稍后重试')
    comments.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化失败:', error)
    return '日期格式错误'
  }
}

// 跳转到商品详情页
const goToProduct = (spuId) => {
  if (!spuId) {
    ElMessage.warning('商品信息不完整，无法跳转')
    return
  }
  router.push({
    path: '/goods/detail',
    query: { id: spuId }
  })
}

// 删除评论
const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    deleteLoading.value = commentId
    
    // 调用删除评论API
    // 根据接口文档: /comments/delete/{id}, method: post
    await deleteCommentApi(commentId)
    
    ElMessage.success('评论已删除')
    
    // 重新加载评论列表
    await loadComments()
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作，不做处理
      return
    }
    
    // 处理API错误
    console.error('删除评论失败:', error)
    
    // 根据错误类型提供更具体的提示
    if (error.message && error.message.includes('未登录')) {
      ElMessage.warning('登录已过期，请重新登录')
      // 可能需要跳转到登录页
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      })
    } else {
      ElMessage.error(error.message || '删除评论失败，请稍后重试')
    }
  } finally {
    deleteLoading.value = null
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadComments()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadComments()
}

// 加载更多评论
const loadMore = async () => {
  if (loadMoreLoading.value) return
  
  try {
    loadMoreLoading.value = true
    const nextPage = currentPage.value + 1
    
    // 调用获取用户评论列表API
    const data = await getCommentsByUserId(nextPage, pageSize.value)
    
    // 处理评论数据
    if (data?.records && Array.isArray(data.records) && data.records.length > 0) {
      // 将新加载的评论添加到列表末尾
      const newComments = data.records.map(comment => {
        const spu = comment.spuVO || {}
        
        return {
          id: comment.id,
          productId: comment.spuId,
          productName: spu.title || '未知商品',
          productImage: spu.mainImage || 'https://via.placeholder.com/80',
          content: comment.content || '',
          rating: comment.rating || 5,
          createdAt: comment.createdAt || new Date().toISOString(),
          imageUrls: Array.isArray(comment.imageUrls) ? comment.imageUrls : [],
          price: spu.price,
          description: spu.description
        }
      })
      
      comments.value = [...comments.value, ...newComments]
      currentPage.value = nextPage
    }
  } catch (error) {
    console.error('加载更多评论失败:', error)
    ElMessage.error('加载更多评论失败，请稍后重试')
  } finally {
    loadMoreLoading.value = false
  }
}

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.user-comments {
  padding: 10px;
}

.section-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.comment-item {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.comment-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.comment-product {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 15px;
  cursor: pointer;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin: 0 0 5px;
  cursor: pointer;
  transition: color 0.2s;
}

.product-name:hover {
  color: #ff4d4f;
}

.product-description {
  font-size: 14px;
  color: #666;
  margin: 5px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
  margin: 5px 0;
}

.comment-date {
  font-size: 13px;
  color: #999;
}

.rating-row {
  margin-bottom: 10px;
}

.comment-text {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
  word-break: break-word;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.comment-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.load-more-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 